<template>
  <div class="publish-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{ acticleId ? '修改文章': '发布文章'}}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form ref="article" :rules="rules" :model="article" label-width="52px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="article.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-tiptap v-model="article.content" :extensions="extensions" lang="zh" :height="400" placeholder="请输入文章内容"></el-tiptap>
          <!-- <el-input type="textarea" v-model="article.content"></el-input> -->
        </el-form-item>
        <el-form-item label="封面" prop="type">
          <el-radio-group v-model="article.cover.type" @change="changeCoverType">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <template v-if="article.cover.type > 0">
            <div class="cover-item">
              <upload-cover
              v-for="(cover, index) in article.cover.type"
              :key="cover" class="cover"
              v-model="article.cover.images[index]"
              ></upload-cover>
              <!-- <upload-cover v-for="(cover, index) in article.cover.type" :key="cover" class="cover" :value="article.cover.images ? article.cover.images[index] : '' " @update-cover="updateCover(index, $event)"></upload-cover> -->
            </div>
          </template>
        </el-form-item>
        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择频道">
            <el-option v-for="item in channels" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :loading="pushLoading" :disabled="draftLoading" type="primary" @click="onPublish">{{ acticleId ? '修改': '发布'}}</el-button>
          <el-button :loading="draftLoading" :disabled="pushLoading" @click="onDraft">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import UploadCover from './components/upload-cover.vue'
import { getArticleChannels, publishArticle, getArticle, updateArticle } from '@/api/article.js'
import { uploadImage } from '@/api/image.js'
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoList,
  TodoItem,
  TextAlign,
  Fullscreen,
  Preview,
  Image,
  TextColor
} from 'element-tiptap'
import 'element-tiptap/lib/index.css'
export default {
  name: 'PublishIndex',
  components: {
    'el-tiptap': ElementTiptap,
    UploadCover
  },
  props: {},
  data () {
    return {
      article: {
        title: '',
        content: '',
        cover: {
          type: 0,
          images: []
        },
        channel_id: null
      },
      acticleId: null,
      channels: [],
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'change' }
        ],
        content: [
          {
            validator: (rule, value, callback) => {
              if (value === '<p></p>' || value === '') {
                callback(new Error('请输入文章内容'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        type: [
          {
            validator: (rule, value, callback) => {
              if (value === 1) {
                if (this.article.cover.images.length !== 1) {
                  callback(new Error('请选择一张封面'))
                } else {
                  callback()
                }
              } else if (value === 3) {
                if (this.article.cover.images.length !== 3) {
                  callback(new Error('请选择三张封面'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        channel_id: [
          { required: true, message: '请选择频道', trigger: 'change' }
        ]
      },
      pushLoading: false,
      draftLoading: false,
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // render command-button in bubble menu.
        new Underline({ bubble: true, menubar: false }), // render command-button in bubble menu but not in menubar.
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new TodoList(),
        new TodoItem(),
        new TextAlign({
          alignments: ['left', 'center', 'right', 'justify']
        }),
        new Image({
          uploadRequest (file) {
            const fd = new FormData()
            fd.append('image', file)
            return uploadImage(fd).then(res => {
              return res.data.data.url
            })
          }
        }),
        new TextColor(),
        new Fullscreen(),
        new Preview()
      ]
    }
  },
  computed: {},
  watch: {
    'article.cover.type': function (type, oldType) {
      if (type === 0 || type === -1) {
        this.article.cover.images = []
      }
      if (type === 1) {
        if (this.article.cover.images.length > 1) {
          const images = this.article.cover.images
          this.article.cover.images = []
          this.article.cover.images[0] = images[0]
        }
      }
    }
  },
  created () {
    this.loadArticleChannels()
    if (this.$route.query.id) {
      this.loadArticle(this.$route.query.id)
    }
  },
  mounted () {},
  methods: {
    onPublish () {
      this.pushLoading = true
      this.$refs.article.validate((valid) => {
        if (valid) {
          if (this.articleId) {
            updateArticle(this.articleId, this.article, false).then(res => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.pushLoading = false
            })
          } else {
            publishArticle(this.article, false).then(res => {
              this.$message({
                message: '发布成功',
                type: 'success'
              })
              this.pushLoading = false
            })
          }
        } else {
          this.pushLoading = false
          return false
        }
      })
    },
    onDraft () {
      this.draftLoading = true
      this.$refs.article.validate((valid) => {
        if (valid) {
          if (this.articleId) {
            updateArticle(this.articleId, this.article, true).then(res => {
              this.$message({
                message: '修改草稿成功',
                type: 'success'
              })
              this.pushLoading = false
            })
          } else {
            publishArticle(this.article, true).then(res => {
              this.$message({
                message: '存入草稿成功',
                type: 'success'
              })
              this.draftLoading = false
            })
          }
        } else {
          this.draftLoading = false
          return false
        }
      })
    },
    loadArticleChannels () {
      getArticleChannels().then(res => {
        this.channels = res.data.data.channels
      })
    },
    loadArticle (articleId) {
      this.articleId = this.acticleId
      getArticle(articleId).then(res => {
        this.article = res.data
      })
    },
    updateCover (index, url) {
      this.article.cover.images[index] = url
    },
    changeCoverType (type) {
      // if (type === 0 || type === -1) {
      //   this.article.cover.images = []
      // }
      // if (type === 1) {
      //   if (this.article.cover.images.length > 1) {
      //     const images = this.article.cover.images
      //     this.article.cover.images = []
      //     this.article.cover.images[0] = images[0]
      //   }
      // }
    }
  }
}

</script>
<style lang='less' scoped>
.cover-item {
  display: flex;
  .cover {
    margin-right: 15px;
  }
}
</style>
